﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

public class AssetController : Controller
{
    private AssetDBEntities1 db = new AssetDBEntities1();

    /// <summary>
    /// 主页面 - 固定资产使用管理
    /// </summary>
    public ActionResult Index()
    {
        return View();
    }

    /// <summary>
    /// 获取资产明细列表数据（AJAX）
    /// </summary>
    [HttpPost]
    public JsonResult GetAssetDetailList(int page = 1, int limit = 10, string assetDetailNum = "", int? assetDetailUseState = null)
    {
        try
        {
            var query = from ad in db.AssetDetailInfo
                        join a in db.AssetInfo on ad.AssetID equals a.AssetID
                        join e in db.EmpolyInfo on ad.EmpolyID equals e.EmpolyID into emp
                        from e in emp.DefaultIfEmpty()
                        join ar in db.AreaInfo on ad.AreaID equals ar.AreaID into area
                        from ar in area.DefaultIfEmpty()
                        select new
                        {
                            ad.AssetDetailID,
                            ad.AssetDetailNum,
                            AssetName = a.AssetName,
                            AssetModel = a.AssetModel,
                            EmpolyName = e != null ? e.EmpolyName : "仓库",
                            AreaName = ar != null ? ar.AreaName : "仓库",
                            ad.AssetDetailUseState,
                            ad.AssetDetailUseDate,
                            ad.AssetDetailReturnDate,
                            ad.AssetDetailServiceState,
                            ad.AssetDetailDumState,
                            ad.AssetAreaReMark
                        };

            // 条件筛选
            if (!string.IsNullOrEmpty(assetDetailNum))
            {
                query = query.Where(ad => ad.AssetDetailNum.Contains(assetDetailNum));
            }

            if (assetDetailUseState.HasValue)
            {
                query = query.Where(ad => ad.AssetDetailUseState == assetDetailUseState.Value);
            }

            // 获取总数
            var count = query.Count();

            // 分页
            var data = query
                .OrderByDescending(ad => ad.AssetDetailID)
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToList();

            return Json(new
            {
                code = 0,
                msg = "success",
                count = count,
                data = data
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 1,
                msg = "获取数据失败：" + ex.Message
            }, JsonRequestBehavior.AllowGet);
        }
    }

    /// <summary>
    /// 获取资产下拉列表数据（AJAX）
    /// </summary>
    [HttpGet]
    public JsonResult GetAssetList()
    {
        try
        {
            var assets = db.AssetInfo
                .Where(a => a.AssetTypeID == 1) // 固定资产
                .Select(a => new { a.AssetID, a.AssetName })
                .ToList();

            return Json(new
            {
                code = 0,
                msg = "success",
                data = assets
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 1,
                msg = "获取数据失败：" + ex.Message
            }, JsonRequestBehavior.AllowGet);
        }
    }

    /// <summary>
    /// 获取员工下拉列表数据（AJAX）
    /// </summary>
    [HttpGet]
    public JsonResult GetEmployeeList()
    {
        try
        {
            var employees = db.EmpolyInfo
                .Where(e => e.DepartureDate == null) // 在职员工
                .Select(e => new { e.EmpolyID, e.EmpolyName })
                .ToList();

            return Json(new
            {
                code = 0,
                msg = "success",
                data = employees
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 1,
                msg = "获取数据失败：" + ex.Message
            }, JsonRequestBehavior.AllowGet);
        }
    }

    /// <summary>
    /// 获取区域下拉列表数据（AJAX）
    /// </summary>
    [HttpGet]
    public JsonResult GetAreaList()
    {
        try
        {
            var areas = db.AreaInfo
                .Select(a => new { a.AreaID, a.AreaName })
                .ToList();

            return Json(new
            {
                code = 0,
                msg = "success",
                data = areas
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                code = 1,
                msg = "获取数据失败：" + ex.Message
            }, JsonRequestBehavior.AllowGet);
        }
    }

    /// <summary>
    /// 分配固定资产（AJAX）- 修复版本
    /// </summary>
    [HttpPost]
    public JsonResult AllocateAsset()
    {
        using (var transaction = db.Database.BeginTransaction())
        {
            try
            {
                // 从请求中获取参数
                int assetID = int.Parse(Request.Form["AssetID"] ?? "0");
                int empolyID = int.Parse(Request.Form["EmpolyID"] ?? "0");
                int areaID = int.Parse(Request.Form["AreaID"] ?? "0");
                int assetNum = int.Parse(Request.Form["AssetNum"] ?? "0");
                DateTime assetDetailUseDate = DateTime.Parse(Request.Form["AssetDetailUseDate"]);
                string assetAreaReMark = Request.Form["AssetAreaReMark"] ?? "";

                // 验证参数
                if (assetID <= 0 || empolyID <= 0 || areaID <= 0 || assetNum <= 0)
                {
                    return Json(new { code = 1, msg = "请填写完整信息" });
                }

                // 1. 检查库存数量
                var availableCount = db.AssetDetailInfo
                    .Count(ad => ad.AssetID == assetID
                        && ad.AssetDetailUseState == 0
                        && ad.AssetDetailDumState == 0);

                if (availableCount < assetNum)
                {
                    return Json(new { code = 1, msg = "库存不足，无法分配。可用数量：" + availableCount });
                }

                // 2. 获取可用的资产明细
                var availableAssets = db.AssetDetailInfo
                    .Where(ad => ad.AssetID == assetID
                        && ad.AssetDetailUseState == 0
                        && ad.AssetDetailDumState == 0)
                    .Take(assetNum)
                    .ToList();

                // 3. 更新资产明细状态
                foreach (var asset in availableAssets)
                {
                    asset.AssetDetailUseState = 1; // 已使用
                    asset.AssetDetailUseDate = assetDetailUseDate;
                    asset.EmpolyID = empolyID;
                    asset.AreaID = areaID;
                    asset.AssetAreaReMark = assetAreaReMark;

                    // 4. 添加使用记录
                    var record = new AssetDetailRecordInfo
                    {
                        AssetDetailID = asset.AssetDetailID,
                        EmpolyID = empolyID,
                        AreaID = areaID,
                        AssetNum = 1,
                        AssetDetailRecordUseDate = assetDetailUseDate,
                        AssetDetailRecordReMark = assetAreaReMark
                    };
                    db.AssetDetailRecordInfo.Add(record);
                }

                db.SaveChanges();
                transaction.Commit();

                return Json(new { code = 0, msg = "分配成功" });
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return Json(new { code = 1, msg = "分配失败：" + ex.Message });
            }
        }
    }

    /// <summary>
    /// 归还资产（AJAX）
    /// </summary>
    [HttpPost]
    public JsonResult ReturnAsset(int assetDetailID)
    {
        using (var transaction = db.Database.BeginTransaction())
        {
            try
            {
                var assetDetail = db.AssetDetailInfo
                    .FirstOrDefault(ad => ad.AssetDetailID == assetDetailID);

                if (assetDetail == null)
                {
                    return Json(new { code = 1, msg = "资产不存在" });
                }

                // 更新资产明细状态
                assetDetail.AssetDetailUseState = 0; // 未使用
                assetDetail.AssetDetailReturnDate = DateTime.Now;
                assetDetail.EmpolyID = null;
                assetDetail.AreaID = null;

                // 更新使用记录
                var record = db.AssetDetailRecordInfo
                    .Where(r => r.AssetDetailID == assetDetailID && r.AssetDetailRecordReturnDate == null)
                    .OrderByDescending(r => r.AssetDetailRecordUseDate)
                    .FirstOrDefault();

                if (record != null)
                {
                    record.AssetDetailRecordReturnDate = DateTime.Now;
                }

                db.SaveChanges();
                transaction.Commit();

                return Json(new { code = 0, msg = "归还成功" });
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return Json(new { code = 1, msg = "归还失败：" + ex.Message });
            }
        }
    }

    /// <summary>
    /// 申报维修（AJAX）
    /// </summary>
    [HttpPost]
    public JsonResult ReportMaintenance(int assetDetailID, string problemDescription)
    {
        try
        {
            var assetDetail = db.AssetDetailInfo
                .FirstOrDefault(ad => ad.AssetDetailID == assetDetailID);

            if (assetDetail == null)
            {
                return Json(new { code = 1, msg = "资产不存在" });
            }

            // 更新维修状态
            assetDetail.AssetDetailServiceState = 1; // 需维修

            // 添加维修记录（这里需要从Session或登录信息中获取当前用户ID）
            int currentEmpolyID = GetCurrentEmpolyID(); // 从Session获取当前用户ID
            var damageRecord = new DamageRecordInfo
            {
                AssetDetailID = assetDetailID,
                EmpolyID = currentEmpolyID,
                DamageDate = DateTime.Now,
                ProblemDescription = problemDescription,
                RecordState = 0 // 申报中
            };
            db.DamageRecordInfo.Add(damageRecord);

            db.SaveChanges();

            return Json(new { code = 0, msg = "维修申报成功" });
        }
        catch (Exception ex)
        {
            return Json(new { code = 1, msg = "申报失败：" + ex.Message });
        }
    }

    /// <summary>
    /// 报废资产（AJAX）
    /// </summary>
    [HttpPost]
    public JsonResult ScrapAssets(List<int> assetDetailIDs)
    {
        try
        {
            var assetDetails = db.AssetDetailInfo
                .Where(ad => assetDetailIDs.Contains(ad.AssetDetailID))
                .ToList();

            foreach (var asset in assetDetails)
            {
                asset.AssetDetailDumState = 1; // 已报废
                asset.AssetDetailUseState = 0; // 设为未使用
                asset.AssetDetailReturnDate = DateTime.Now;
                asset.EmpolyID = null;
                asset.AreaID = null;
            }

            db.SaveChanges();

            return Json(new { code = 0, msg = "报废成功" });
        }
        catch (Exception ex)
        {
            return Json(new { code = 1, msg = "报废失败：" + ex.Message });
        }
    }

    /// <summary>
    /// 获取当前登录用户ID（示例方法）
    /// </summary>
    private int GetCurrentEmpolyID()
    {
        // 这里需要根据您的登录系统实现
        // 示例：从Session中获取
        if (Session["CurrentEmpolyID"] != null)
        {
            return Convert.ToInt32(Session["CurrentEmpolyID"]);
        }

        // 如果没有登录系统，暂时返回1作为示例
        return 1;
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}